<?php
/**
 * BaseProcess
 * - The base object for all DAO extension
 * - Assume that using ADOdb for connection
 * - Global connection $dbcon
 * @author Phung Van Tam
 */
if ( defined ('DIR_CACHE_ADODB') && is_dir(DIR_CACHE_ADODB)) {
    $ADODB_CACHE_DIR = DIR_CACHE_ADODB;
}

class BaseProcess {
	protected $tableName;
	protected $attribute;
	protected $primaryKeyName;
	public $dbcon = null;
    public $rs;
    public $sql;
    public $fields;
	public $flagCloseConnect = false;
	public $dbInfo = null;
	
    /**
     * Constructor
     */
    public function __construct($tableName = null) {
		$this->tableName = $tableName;
		$this->attribute = array();
		$this->primaryKeyName = $tableName . "_id";
        $this->rs = null;
        $this->fields = array();
	}
    
	/**
	 * setConnection
	 */
    public function setConnection($dbcon)
    {
        $this->dbcon = $dbcon;
    }
    
    /**
	 * continueConnect
	 */
    public function continueConnect()
    {
        $this->flagCloseConnect = false;
        return $this;
    }
    
    /**
	 * SetFetchMode
	 */
    public function SetFetchMode($fetchMode = ADODB_FETCH_ASSOC)
    {
        $validMode = array(ADODB_FETCH_DEFAULT, ADODB_FETCH_NUM, ADODB_FETCH_ASSOC, ADODB_FETCH_BOTH);
        if(!in_array($fetchMode, $validMode))
            $fetchMode = ADODB_FETCH_ASSOC;
              
        $this->dbcon->SetFetchMode($fetchMode);
    }
    
	/**
	 * getTableName
	 */
	public function getTableName() {
		return $this->tableName;
	}
    
	/**
	 * setFieldName
	 */
    public function setFieldName($fieldName, $fieldValue = null)
    {
      $this->{$fieldName} = $fieldValue;
    }
    
	/**
	 * setAttribute
	 */
	public function setAttribute($attName, $attValue) {
		$this->attribute[$attName] = $attValue;
	}
	
	/**
	 * setAttributes
	 */
	public function setAttributes($data) {
		$this->attribute = $data;
	}

	/**
	 * getAttribute
	 */
	public function getAttribute($attName) {
		return $this->attribute[$attName];
	}
	
	/**
	 * emptyAttribute
	 */
	function emptyAttribute() {
		$this->attribute = array();
	}
	
	/**
	 * connect
	 */
	public function connect($fetchMode = ADODB_FETCH_ASSOC) {
		$DB = constants::$dbList;
    	$listTalbe = explode(' ', $DB['table_list']);
    	if (in_array($this->tableName, $listTalbe)) {
    		$this->dbInfo = $DB;
    		$this->dbcon = $DB['dbcon'];		
    	}	
    	if ($this->dbInfo != null) {
    		$this->dbcon->debug = $this->dbInfo["debug"];
    		$this->dbcon->Connect($this->dbInfo["host"], $this->dbInfo["username"], $this->dbInfo["password"], $this->dbInfo["database"]);
			return $this;
    	}
    	else {
    		echo "connect busy!!!!";
    		exit();
    	}
	}
	
	/**
	 * close
	 */
	public function close() {
		$this->dbcon->Close();
    	$this->dbInfo['database'] = $this->dbInfo;
    	$this->dbInfo = null;
    	$this->dbcon = null;
    	return $this;	
	}
	
	/**
	 * execute
	 */
	public function execute($sql, $fetchMode = ADODB_FETCH_ASSOC) 
    {
		// Connect database
		$this->connect();
		
		$this->SetFetchMode($fetchMode);
        $this->sql = $sql;
        $this->rs = $this->dbcon->Execute($sql);
        if ($this->flagCloseConnect) {
        	$this->close();	
        }
        FunctionCommon::writeLogs($sql);
		return $this->rs;
	}
	
	/**
	 * insert
	 */
	public function insert() {
		// Connect database
		$this->connect();
		
		$c = count($this->attribute);
		if ($c === 0) {
			return 0;
		}
		else {
			$attributeNames = array_keys($this->attribute);
			$attributeValues = array_values($this->attribute);
			for ($i = 0; $i < $c; $i++) {
				if ($attributeValues[$i] === null) {
					$attributeValues[$i] = "null";
				}
				else {
					$attributeValues[$i] = "'" . mysql_real_escape_string($attributeValues[$i]) . "'";
				}
			}
			$sql = "INSERT INTO $this->tableName(" . implode(",", $attributeNames) . ") VALUES (" . implode(",", $attributeValues) . ");";
			
			$rs = $this->continueConnect()->execute($sql);
			$id = mysql_insert_id();
			$this->close();

			// Set to the primary key
			$this->setAttribute($this->primaryKeyName, $id);
			return $id;
		}
	}
    
	/**
	 * update
	 */
	public function update($primaryKey = array()) {
		// Connect database
		$this->connect();
		$c = count($this->attribute);
		if ($c === 0) {
			return 0;
		}
		else {
			$sql = "UPDATE $this->tableName SET ";
			$i = 0;
			foreach ($this->attribute as $name=>$value) {
				if ($value === null) {
					$value = "null";
				}
				else {
					$value = "'" . mysql_real_escape_string($value) . "'";
				}
				$sql .= $name . "=" . $value;
				if ($i < $c - 1) {
					$sql .= ",";
				}
				$i++;
			}
			// Condition for update
			$sql .= " WHERE ";
			if (count($primaryKey) > 0) {
				$temp = "";
				foreach($primaryKey as $key=>$value) {
					$sql .= $temp . " $key = '" . $value . "'";
					$temp = "AND";			
				}
			}
			else {
				$sql .= "$this->primaryKeyName = '" . $this->getAttribute($this->primaryKeyName) . "'";	
			}
			
		
			$noOfUpdatedRecord = $this->execute($sql);
			return $noOfUpdatedRecord;
		}
	}

	/**
	 * delete
	 */
	public function delete($arrKey) {
		// Connect database
		$this->connect();
		$sql = "DELETE FROM " . $this->tableName . " WHERE 1=1";
        foreach ($arrKey as $k=>$v) {
        	$v = "'" . mysql_real_escape_string($v) . "'";
        	$sql .= " AND $k=$v";
        }
		$this->execute($sql);
	}
	
	/**
	 * getByPrimaryKey
	 */
	public function getByPrimaryKey($key) 
    {
		// Connect database
		$this->connect();
		
		$key = "'" . mysql_real_escape_string($key) . "'";
		$sql = "SELECT * FROM  $this->tableName  WHERE  $this->primaryKeyName  =  $key";
		$rs = $this->execute($sql, ADODB_FETCH_ASSOC);
		$data = array();
		for (; !$rs->EOF; $rs->MoveNext()) {
			foreach ($rs->fields as $name=>$value) {
				$data[$name] = $value;
			}
			break;
		}
		return $data;
	}
    
	/**
	 * getOneByAttr
	 */
	public function getOneByAttr($attr, $fields = array()) {
		// Connect database
		$this->connect();
		
		$strFields = "";
		if(is_array($fields) && !empty($fields)){
			$strFields = implode(", ", $fields);
			$sql = "SELECT " . $strFields . " FROM $this->tableName WHERE 1=1";
		}
		else {
			$sql = "SELECT * FROM $this->tableName WHERE 1=1";
		}
		foreach ($attr as $key=>$value) {
			if ($value !== null) {
				$value = "'" . mysql_real_escape_string($value) . "'";
				$sql .= " AND $key=$value";
			}
			else {
				$sql .= " AND $key IS NULL";
			}
		}
		$sql .= " LIMIT 0,1";
		$rs = $this->execute($sql, ADODB_FETCH_ASSOC);
		$data = array();
		for (; !$rs->EOF; $rs->MoveNext()) {
			foreach ($rs->fields as $name=>$value) {
				$data[$name] = $value;
			}
		}
		return $data;
	}
    
	/**
	 * getPrimaryKeyName
	 */
    public function getPrimaryKeyName()
    {
        return $this->primaryKeyName;
    }

    /**
	 * getAttributes
	 */
    public function getAttributes()
    {
        return $this->attribute;
    }
    
    /**
	 * getAllByAttribute
	 */
    public function getAllByAttribute($atrr, $fields = array(), $limit = array(), $order = 'seq', $styleOrder = 'DESC')
    {
        // Connect database
		$this->connect();

        $strFields = "";
		if(is_array($fields) && !empty($fields)){
			$strFields = implode(", ", $fields);
			$sql = "SELECT " . $strFields . " FROM $this->tableName WHERE 1=1";
		} else {
			$sql = "SELECT * FROM $this->tableName WHERE 1=1";
		}
        
        foreach ($atrr as $key=>$value) {
        	if (is_array($value)) {
        		$value['value'] = "'" . mysql_real_escape_string($value['value']) . "'";
	            $sql .= " AND " . $key . $value['math'] . $value['value'];	
        	} else {
        		if ($value !== null) {
	                $value = "'" . mysql_real_escape_string($value) . "'";
	                $sql .= " AND $key=$value";
	            }else {
	                $sql .= " AND $key IS NULL";
	            }	
        	}
        }
        $sql .= " ORDER BY " . $order . " " . $styleOrder;
        if (count ($limit) > 0) {
        	$sql .= " LIMIT " . $limit[0] . "," . $limit[1];
        }
        $rs = $this->execute($sql, ADODB_FETCH_ASSOC);
        $result = array();
        if($rs) {
            while (! $rs->EOF && $item = $rs->FetchRow()) { 
                $result[] = $item;
            }
        }
        return $result;
    }

    /**
	 * getFields
	 */
    public function getFields()
    {
        return $this->fields;   
    }
    
    /**
	 * getKeyFields
	 */
    public function getKeyFields()
    {
        return array_keys($this->fields);
    }
    
    
	/**
	* getTotalData
	*/
	public function getTotalData($condition = array()) {
		$this->connect();
		$sql = "SELECT COUNT(id) as count_data FROM $this->tableName WHERE 1=1";
		if (is_array($condition) && !empty($condition)) {
			foreach ($condition as $key=>$con) {
				$sql .= " AND " . $key . $con['math'] . "'" . mysql_real_escape_string($con['value']) . "'";
			}
		}
		$rs = $this->execute($sql, ADODB_FETCH_ASSOC);
		return $rs->fields['count_data'];	
	}
	
	/**
	 * getListData
	 */
	public function getListData($start, $length, $arrField = array(), $condition = array(), $orderBy = array()) {
		$this->connect();
		if (is_array($arrField) && !empty($arrField)) {
			$field = implode(", ", $arrField);
			$sql = "SELECT $field FROM $this->tableName WHERE 1=1";
		} else {
			$sql = "SELECT * FROM $this->tableName WHERE 1=1";
		}
		
		if (is_array($condition) && !empty($condition)) {
			foreach ($condition as $key=>$con) {
				$sql .= " AND " . $key . $con['math'] . "'" . mysql_real_escape_string($con['value']) . "'";
			}
		}
		
		if (is_array($orderBy) && !empty($orderBy)) {
			$i = 0;
			$sql .= " ORDER BY ";
			foreach ($orderBy as $k=>$v) {
				$sql .= $k . " " . $v;
				if ($i < count($orderBy) - 1) {
					$sql .= ",";
				}
				$i++;
			}
		} else {
			$sql .= " ORDER BY seq DESC";
		}
		
		$sql .= " LIMIT $start, $length";
		$rs = $this->execute($sql, ADODB_FETCH_ASSOC);
		$data = array();
		if($rs) {
            while (! $rs->EOF && $item = $rs->FetchRow()) { 
                $data[] = $item;
            }
        }
        return $data;
	}
	
	/**
	 * getMinMax
	 */
	public function getMinMax($condition = array(), $math = false, $seq = 'seq') {
		// Connect database
		$this->connect();
		
		if ($math) {
			$sql = "SELECT MAX(".$seq.") as m_value FROM ".$this->tableName." WHERE 1=1";
		} else {
			$sql = "SELECT MIN(".$seq.") as m_value FROM ".$this->tableName." WHERE 1=1";
		}
		
		if (is_array($condition) && !empty($condition)) {
			foreach ($condition as $name=>$val) {
				$sql .= " AND ".$name.$val['math']. "'" . $val['value'] . "'";
			}
		}
		
		$rs = $this->execute($sql, ADODB_FETCH_ASSOC);
		return $rs->fields['m_value'];	
	}
	
	/**
	 * getSeq
	 */
	public function getIdBySeq($seq = null) {
		// Connect database
		if ($seq != null) {
			$this->connect();
			$sql = "SELECT id FROM " . $this->tableName . " WHERE seq = '" . $seq . "' LIMIT 0,1";
			$rs = $this->execute($sql, ADODB_FETCH_ASSOC);
		}
		return $rs ? $rs->fields['id'] : null;
	}
}
?>